package com.example.asus.get_postdemo;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by asus on 2017/11/21.
 */

public class RequestUtilByOKHttp {

    private RequestUtilByOKHttp() {
    }

    public enum Method {GET, POST}


    private static RequestUtilByOKHttp requestUtil;

    public static RequestUtilByOKHttp getInstance() {

        if (requestUtil == null) {
            synchronized (RequestUtilByOKHttp.class) {
                if (requestUtil == null) {
                    requestUtil = new RequestUtilByOKHttp();
                }
            }
        }

        return requestUtil;
    }

    public String Login(Method method, String username, String password, Handler handler) throws IOException {
        if (method == Method.GET) {
            URL url = new URL("http://172.17.136.88:8080/login/login?username=" + username + "&pwd=" + password + "");
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string() + "By okHttp";
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }

        if (method == Method.POST) {
            OkHttpClient client = new OkHttpClient();
            URL url = new URL("http://172.17.136.88:8080/loginPost/login");
            Request request = new Request.Builder()
                    .url(url)
                    .post(new FormBody.Builder().add("username", username).add("pwd", password).build())
                    .build();

            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string() + "By okHttp";
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
        return "Connect fail";
    }

    public String Login(final String pictureName, final Context context, Handler handler, final ImageView iv) throws IOException {
        OkHttpClient client = new OkHttpClient();
        URL url_pic = new URL("http://img5.duitang.com/uploads/item/201408/05/20140805152029_j2Pc3.jpeg");
        Request request = new Request.Builder()
                .url(url_pic)
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            return null;
        }

        InputStream inputStream = response.body().byteStream();
        final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, context.openFileOutput(pictureName, Context.MODE_PRIVATE));
        InputStream is = new FileInputStream(new File(context.getFilesDir(), pictureName));
        final Bitmap bitmap1 = BitmapFactory.decodeStream(is);
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.i("TAG", "bitmap");
                iv.setImageBitmap(bitmap1);
            }
        });


        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"),
                new File(context.getFilesDir(), pictureName));
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("fName", pictureName).addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"" + pictureName + "\"")
                , RequestBody.create(MediaType.parse("image/jpeg"), new File(context.getFilesDir(), pictureName)));
        RequestBody body = builder.build();

        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.i("TAG", "multipartbody");
            }
        });
        URL url = new URL("http://172.17.136.88:8080/upload/upload");
        Request request2 = new Request.Builder()
                .url(url).post(body)
                .build();
        handler.post(new Runnable() {
            @Override
            public void run() {
                File file = new File(context.getFilesDir(), pictureName);
                Log.i("TAG", "request2");
                if (file.exists()) {
                    Log.i("TAG", file.getPath());
                }
            }
        });

        Response response2 = client.newCall(request2).execute();

        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        return response2.body().string();
    }
}
